define(['request', 'template','jsonp','jquery', 'bootstrap'], (request, template,jsonp) => {
    class Header {
      constructor () {
        this.loadHTML().then(()=>{
          this.showHeade()
          this.getLink()
          this.inputSearch()
          this.showUserInfo()
          this.cart=JSON.parse(localStorage.getItem('cart')||'[]')
          this.getNavLink().then(value=>{
            this.showNav()
          })
          this.delShopInTopCart()
          this.bindEvent()
        })
      }
      loadHTML () {
        return new Promise(resolve => {
          $('header').load('/html/publicHeader.html', () => {
            resolve()
          })
        })
      }
      bindEvent(){
        let $cart=$('header .header-right .cart-warp')
        $('header .header-right .cart').hover(()=>{
          $cart.show()
        },()=>{})
        $('header .header-right').hover(()=>{},()=>{
            $cart.hide()
        })
        $('.hasCart .bottom button').on('click',function(){
          location.href='/html/cart.html'
        })
      }
      showHeade(){
        this.cart=JSON.parse(localStorage.getItem('cart')||'[]')
        if(this.cart.length>0){
          $('.redDot').show()
          $('.empty-cart-top').hide()
          $('.hasCart').show()
          this.topCart(this.cart)
        }else{
          $('.empty-cart-top').show()
          $('.hasCart').hide()
          $('.redDot').hide()
        }
      }

      topCart(cart){
        //底部显示
       const info =cart.reduce((info,shop)=>{
          info.count+=shop.count
          info.price+=(shop.count*shop.price)
          return info
        },{count:0,price:0})
        
        $('.hasCart .bottom .count>span').html(info.count)
        $('.hasCart .bottom .sum>span').html("￥"+info.price.toFixed(2))
        //列表显示
        $('#header-cart-warp').html(template('header-cart',{list:cart}))
      }
      
      showUserInfo(){
        const user=document.cookie
        const $goLogin=$('.header-right>.login>a')
        const $username=$('.header-right>.login .userName')
        const $userInfo=$('.header-right>.login>h3')
        const $quit=$('.header-right>.login .quit')
        if(user){
          let userinfo=user.split('=')[1].split('')
          userinfo.splice(3,4,'****')
          userinfo=userinfo.join('')
          $userInfo.show()
          $goLogin.hide()
          $username.html(userinfo)
        }else{
          $userInfo.hide()
          $goLogin.show()
        }
        $quit.on('click',function(){
          const date=new Date()
          date.setDate(date.getDate()-1)
          document.cookie=`name=xxx;path=/;expires=${date.toUTCString()}`
          $userInfo.hide()
          $goLogin.show()
        })
      }

      //添加购物车
      addTocart(warp,datas,isCart,cartWarp,fun){
        this.addType=1//type为1代表添加新商品，为2代表添加重复商品
        warp.on('click',(e)=>{
          this.cart=JSON.parse(localStorage.getItem('cart')||'[]')
          if(e.target.className==='add-to-cart'){
            const id=$(e.target).parents('li').data('id')
            const shop = datas.find(val=>{
                        return val.id===id
                      })
            if(this.cart.length>0){
              const isRepeat = this.cart.find(val=>{
                return val.id===id
              })
              if(isRepeat){
                this.addType=2
                isRepeat.count++
              }else{
                this.addType=1
                this.cart.push({...shop,count:1,checked:true})
              }
              localStorage.setItem('cart',JSON.stringify(this.cart))
           }else{
            this.cart.push({...shop,count:1,checked:true})
            localStorage.setItem('cart',JSON.stringify(this.cart))
            this.addType=1
           }
          //判断更新shop的类型
          if(this.addType===1){
            //更新顶部购物车
            $('#header-cart-warp').append(
              `<li data-id='${shop.id}'>
                <a href="/html/shopinfo.html?id=${shop.id}"><img src="${shop.image}"></a>
                <div class="shopinfo">
                    <span>${shop.title.slice(0,10)}</span>
                    <p class="color">${shop.couponValue}</p>
                    <p class="priceinfo"><span class="price">${shop.price}</span><span class="count">x&nbsp;1</span></p>
                </div>
               </li>`)
             this.topCart(this.cart)
             this.showHeade()
          }else if(this.addType===2){
            //更新顶部对应数据
            const el = $('#header-cart-warp').children('li').filter(function(){
                      return $(this).data('id')==id
                    })
            el.find('.count')[0].innerText=1+el.find('.count')[0].innerText*1
            this.topCart(this.cart)
            this.showHeade()
          }
          //显示隐藏提示信息
          $(e.target).prev().show()
          setTimeout(()=>{
              $(e.target).prev().hide()
            },500)
          }
        })
      }

      //通过顶部购物车删除数据
      delShopInTopCart(){
        $('#header-cart-warp').on('click',(e)=>{
          if(e.target.className==='del'){
           //得到对应数据id
           const id =$(e.target).parents('li').data('id')
           //在本地存储中删除对应的数据
           this.cart=this.cart.filter(val=>{
              return val.id!=id
           })
           localStorage.setItem('cart',JSON.stringify(this.cart))
          }
          //更新顶部购物车页面数据
          this.topCart(this.cart)
          this.showHeade()
        })
      }

      inputSearch(){
        const $searchInput=$('#searchInput')
        const $searchTitle=$('#title')
        //用百度的jsonp接口代替一哈  'https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su'
        $searchInput.on('input',()=>{
          const keywords=$searchInput.val()
          $searchTitle.show()
          jsonp.jsonp('https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su','searchValue',{wd:keywords})
        })

        $searchInput.on('blur',()=>{
          setTimeout(()=>{
            $searchTitle.hide()
            $searchTitle.html("")
          },100)
        })

        $searchInput.on('keyup',function(e){
          if(e.keyCode===13){
            const word=$searchInput.val()
            location.href=`/html/list.html?search=${word}`
          }
        })
        $searchTitle.on('click',function(e){
            if(e.target.nodeName==='LI'){
                const word=e.target.innerText
                location.href=`/html/list.html?search=${word}`
            }
        })

        $searchInput.next().children().on('click',function(){
          location.href=`/html/list.html?search=${this.innerText}`
        })
      }

      showNav(){
        let $allLinks=$('.nav-warp>ul>li>a')
        let $linkInfo=$('.nav-info-warp')
        let $nav=$('nav')
       
        $allLinks.hover((e)=>{
          $linkInfo.slideDown({duration :200})
          const word=e.target.innerText
          request.getSearchList(word).then(value=>{
            const {list}=value.data
            const datas=[]
            for(let i=0;i<4;i++){
              datas.push(list.slice(i*4,i*4+4).filter(val=>{
                return val.type===1
              }))
            }
            
            $('#nav-info-warp').html(template('nav-info',{groupList:datas}))
          })
        },()=>{})
        $nav.hover(()=>{},()=>{
            $linkInfo.slideUp({duration :200})
        })
        $linkInfo.hover(()=>{},()=>{
            $linkInfo.slideUp({duration :200})
        })
      }

      //获取link数据
      getLink(){
        request.getLink().then((value)=>{
          if(value.code===200){
            const list=value.data.list.slice(1)
            $('#header-right_warp').append(template('link_list',{linkList:list}))
          }
        })
      }

      //
      getNavLink(){
        return new Promise(resolve=>{
          request.getNavList().then(value=>{
              if(value.code===200){
                const navList=value.data.hotWords
                $("#nav_list_warp").append(template("nav_list",{navList}))
                resolve()
              }
            })
        })
       
      }
    }
    return new Header()
})
  